package com.smart.service.remind;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONObject;
import com.smart.common.entities.constant.SmartConstant;
import com.smart.manager.finance.entities.models.FinanceOrderCoin;
import com.smart.manager.member.entities.models.MemberMaterialChicken;
import com.smart.manager.member.entities.models.MemberMaterialPig;
import com.smart.manager.member.entities.models.MemberProfileMain;
import com.smart.manager.member.entities.models.query.QMemberProfileMain;
import com.smart.manager.member.entities.views.MemberView;
import com.smart.manager.pop.entities.models.PopDisBill;
import com.smart.manager.pop.entities.models.PopDisInviter;
import com.smart.manager.system.repository.ConfigRepository;
import com.smart.manager.union.egg.enums.EggOrderState;
import com.smart.manager.union.egg.models.UnionEggOrder;
import com.smart.manager.union.mall.enums.MallOrderState;
import com.smart.manager.union.mall.models.UnionMallOrder;
import com.smart.manager.weixin.mp.MbMsgService;
import com.smart.manager.wiki.entities.enums.NoticeScope;
import com.smart.manager.wiki.entities.repository.IntelRemindRepository;
import com.smart.manager.work.entities.models.query.QBasicStaff;
import com.smart.service.sms.SmsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author Administrator
 */
@Service
@RequiredArgsConstructor
@Log4j2
public class RemindService {
    private final IntelRemindRepository remindRepository;
    private final SmsService smsService;
    private final ConfigRepository configRepository;
    private final WxMaService wxMaService;
    private final MbMsgService mbMsgService;


    /**
     * 获得钻石奖励提醒
     *
     * @param memberId 会员编号
     * @param total    获得钻石的提醒
     */
    @Async
    public void sendMsgWhenGetDiamond(Long memberId, int total) {
        String title = "获得奖励提醒";
        String content = String.format("恭喜您成功邀请%s名好友注册,获得%s枚钻石", 1, total);
        remindRepository.sendSiteRemind(NoticeScope.MEMBER, memberId, title, content);
    }


    /**
     * 发送金币充值成功提醒
     *
     * @param memberId  会员编号
     * @param orderCoin 充值订单数据
     */
    @Async
    public void sendBuyCoinMsg(Long memberId, FinanceOrderCoin orderCoin) {
        String title = "金币充值成功提醒";
        String content = String.format(
                "金币充值成功,您通过%s支付:%s元 ，本次获得获得%s个金币",
                orderCoin.getPayPlatform().getLabel(),
                orderCoin.getFee(),
                orderCoin.getCoinTotal()
        );
        remindRepository.sendSiteRemind(NoticeScope.MEMBER, memberId, title, content);
    }


    /**
     * 猪猪入圈成功提醒
     *
     * @param memberId 会员编号
     * @param pig      猪猪
     */
    @Async
    public void sendEnterTheCircleMsg(Long memberId, MemberMaterialPig pig) {
        String title = "猪猪入圈成功提醒";
        String content = String.format("猪猪入圈成功,您的猪猪%s ，已经进入到%s ，快来看看吧!", pig.getName(), pig.getPigsty().getName());
        remindRepository.sendSiteRemind(NoticeScope.MEMBER, memberId, title, content);

        //发送模板短信
        String phoneNumber = new QMemberProfileMain().id.eq(memberId).select(QMemberProfileMain.Alias.phoneNumber).setMaxRows(1).findSingleAttribute();
        JSONObject jsonObject = configRepository.readCache(SmartConstant.SMS_TEMPLATE_CFG);
        //获取入栏短信模板编号
        String templateCode = jsonObject.getString("A01");
        //发送如栏短信
        smsService.sendTemplateRemind(phoneNumber, templateCode);

    }

    /**
     * 站内消息猪猪入圈成功提醒
     *
     * @param memberId
     * @param pig
     */
    @Async
    public void sendInsideEnterTheCircleMsg(Long memberId, MemberMaterialPig pig) {
        String title = "猪猪入圈成功提醒";
        String content = String.format("猪猪入圈成功,您的猪猪%s ，已经进入到%s ，快来看看吧!", pig.getName(), pig.getPigsty().getName());
        remindRepository.sendSiteRemind(NoticeScope.MEMBER, memberId, title, content);
    }

    @Async
    public void sendExchangeSuccessfulMsg(Long memberId, MemberMaterialPig pig) {
        String title = "猪猪兑换成功提醒";
        String content = String.format("猪猪兑换成功,您的成功兑换品种为 %s ，快来看看吧!", pig.getBreed().getName());
        remindRepository.sendSiteRemind(NoticeScope.MEMBER, memberId, title, content);
    }

    @Async
    public void sendGiveMsg(Long memberId) {
        String title = "赠送猪猪提醒";
        String content = "您的好友赠送了您一只猪猪 , 快来看看把!";
        remindRepository.sendSiteRemind(NoticeScope.MEMBER, memberId, title, content);
    }

    @Async
    public void sendAddGiveMsg(Long memberId, MemberView member) {
        String title = "赠送猪猪成功提醒";
        String content = String.format("您的成功赠送好友 %s 一只猪猪", member.getNickName());
        remindRepository.sendSiteRemind(NoticeScope.MEMBER, memberId, title, content);
    }

    @Async
    public void sendInsideCoCultureMsg(Long memberId, MemberMaterialPig pig) {
        String title = "合养邀请提醒";
        String content = "您的好友邀请您一起合养猪猪 , 快来看看把!";
        remindRepository.sendSiteRemind(NoticeScope.MEMBER, memberId, title, content);
    }

    @Async
    public void sendInsideCoCultureAgreeMsg(Long memberId, MemberMaterialPig pig) {
        String title = "合养成功提醒";
        String content = String.format("成功合养了 %s  , 快来看看把!", pig.getName());
        remindRepository.sendSiteRemind(NoticeScope.MEMBER, memberId, title, content);
    }


    /**
     * 使用备用金喂食猪仔
     *
     * @param memberId 会员编号
     * @param pig      猪猪
     */
    @Async
    public void sendAutoWeishi(Long memberId, MemberMaterialPig pig) {
        String title = "扣除备用金提示";
        String content = String.format("您的金币账户余额不足,[%s]正在使用备用金购买食物!", pig.getName());
        remindRepository.sendSiteRemind(NoticeScope.MEMBER, memberId, title, content);
        //发送模板短信
        String phoneNumber = new QMemberProfileMain().id.eq(memberId).select(QMemberProfileMain.Alias.phoneNumber).setMaxRows(1).findSingleAttribute();
        JSONObject jsonObject = configRepository.readCache(SmartConstant.SMS_TEMPLATE_CFG);
        //获取入栏短信模板编号
        String templateCode = jsonObject.getString("A03");
        //发送如栏短信
        smsService.sendTemplateRemind(phoneNumber, templateCode);

    }
    //==========================

    /**
     * 连续七天提醒 备用金已经用完了
     *
     * @param memberId 会员编号
     * @param pig      猪猪
     */
    @Async
    public void sendAutoOut(Long memberId, MemberMaterialPig pig) {
        String title = "备用金耗尽提示";
        String content = String.format("您的备用金余额不足,[%s]的备用金已经耗尽!", pig.getName());
        remindRepository.sendSiteRemind(NoticeScope.MEMBER, memberId, title, content);
        //发送模板短信
        String phoneNumber = new QMemberProfileMain().id.eq(memberId).select(QMemberProfileMain.Alias.phoneNumber).setMaxRows(1).findSingleAttribute();
        JSONObject jsonObject = configRepository.readCache(SmartConstant.SMS_TEMPLATE_CFG);
        //获取入栏短信模板编号
        String templateCode = jsonObject.getString("A04");
        //发送如栏短信
        smsService.sendTemplateRemind(phoneNumber, templateCode);

    }


    @Async
    public void sendMiniProgramsMsg(String openId, String commodity, String code, Boolean isAll) {
        try {
            String accessToken = wxMaService.getAccessToken();
            String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            if (isAll) {
                List<String> openIdList = new QBasicStaff().isManage.eq(true).openId.isNotNull().select(QBasicStaff.Alias.openId).findSingleAttributeList();
                openIdList.forEach(x -> {
                    String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
                    String jsonStr = "{\"touser\":\"" + x + "\",\"data\":{\"time5\":{\"value\":\"" + format + "\"},\"thing6\":{\"value\":\"" + commodity + "\"},\"thing3\":{\"value\":\"" + code + "\"}},\"template_id\":\"9G0M8FK1Aq5KF-mwI0KLpeVwmtmWayAD-DEl6vEtMAA\"}";
                    HttpResponse body = HttpRequest.post(url).body(jsonStr).execute();
                    log.warn(body.body());
                });
            } else {
                String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
                String jsonStr = "{\"touser\":\"" + openId + "\",\"data\":{\"time5\":{\"value\":\"" + format + "\"},\"thing6\":{\"value\":\"" + commodity + "\"},\"thing3\":{\"value\":\"" + code + "\"}},\"template_id\":\"9G0M8FK1Aq5KF-mwI0KLpeVwmtmWayAD-DEl6vEtMAA\"}";
                HttpResponse body = HttpRequest.post(url).body(jsonStr).execute();
                log.warn(body.body());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 创建提蛋订单提醒
     */

    public void sendWhenEggOrderCreate(Long memberId, UnionEggOrder order) {
        String title = "鸡蛋提取成功通知";
        String content;
        if (EggOrderState.T0.equals(order.getState())) {
            content = "恭喜你成功提取" + order.getTitle() + " 请尽快到微信公众号内填写收货信息吧!";
        } else {
            content = "恭喜你成功提取" + order.getTitle() + " 请及时关注公众号的内的订单物流通知!";
        }
        remindRepository.sendSiteRemind(NoticeScope.MEMBER, memberId, title, content);
        mbMsgService.whenOrderCreate(memberId,
                order.getId(),
                order.getTitle(),
                order.getSubmitTime(),
                order.getState().getLabel(),
                "https://www.baidu.com"
        );


    }


    public void sendWhenEggOrderReplenishExpress(UnionEggOrder record) {
        String title = "鸡蛋发货通知";
        String content = "你的鸡蛋兑换订单已经发货，请注意查收! 快递名称:" + record.getExpressCode() + ",快递单号:" + record.getExpressCode();
        remindRepository.sendSiteRemind(NoticeScope.MEMBER, record.getMember().getId(), title, content);
        mbMsgService.whenEggOrderReplenishExpress(record);

    }


    @Async
    public void sendStealing(Long memberId, MemberMaterialChicken chicken) {
        String title = "鸡蛋被偷提醒";
        String content = String.format(
                "您的鸡蛋已经被%s玩家偷取，快来收蛋吧！",
                chicken.getReceive().getNickName()
        );

        log.warn("chicken = {}",chicken);
        log.warn("发送的是 = {}",content);

        remindRepository.sendSiteRemind(NoticeScope.MEMBER, memberId, title, content);
    }

    @Async
    public void sendWhenMallOrderCreate(Long memberId, UnionMallOrder order) {
        String title = "商城订单下单成功通知";
        StringBuilder content = new StringBuilder();
        content.append("恭喜你成功购买").append(order.getGoods().getTitle()).append("*").append(order.getQuantity());
        if (MallOrderState.T0.equals(order.getState())) {
            content.append(" 请尽快到微信公众号内填写收货信息吧!");
        } else {
            content.append(" 请及时关注公众号的内的订单物流通知!");
        }
        remindRepository.sendSiteRemind(NoticeScope.MEMBER, memberId, title, content.toString());
        mbMsgService.whenOrderCreate(memberId,
                order.getId(),
                order.getGoods().getTitle() + "*" + order.getQuantity(),
                order.getSubmitTime(),
                order.getState().getLabel(),
                "https://www.baidu.com"
        );


    }


    /**
     * B2C绑定成功发送模板消息
     * */
    @Async
    public void sendB2cBind(MemberProfileMain newMember, PopDisInviter popDisInviter) {
        mbMsgService.whenB2cBindSuccess(newMember ,popDisInviter);
    }



    /**
     * 代理流水发送说明
     * */
    @Async
    public void sendStreamBind(PopDisInviter popDisInviter, PopDisBill popDisBill) {
        mbMsgService.streamBindSuccess(popDisInviter,popDisBill);
    }
}
